package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.dtos.ResponseResult;
import com.heima.model.admin.enums.AppHttpCodeEnum;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    //RuntimeException 会回滚  Exception
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //1 检查参数 (用户名  密码不能为空)
        if(StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }

        //2: 根据用户名查询用户
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if(user==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //3:校验密码  (用户输入密码+salt)md5加密 ---->和数据库密码做对比
        String password = user.getPassword();
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
        if(!inputPwd.equals(password)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }
        //4: 检查用户状态   正常状态9
            if(!user.getStatus().equals(AdminConstants.USER_STATUS_ISSTATUS)){
                CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
            }
        //5: 修改登录时间
            user.setLoginTime(new Date());
            //里面传 user看不懂
            // TODO:updateById方法在插入时,会根据实体类的每个属性进行非空判断,只有非空放入属性对应的字段才会出现在SQL语句中
            //TODO: 补充: updateAllColumnById方法在插入时,不管属性是否为空,属性所对应的字段都会出现在SQL语句中
            updateById(user);
        //6: 颁发token
        AdUserVO adUserVO=new AdUserVO();
        //属性copy
        BeanUtils.copyProperties(user,adUserVO);
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));

        //7: user:用户信息   token:令牌
        Map result=new HashMap<>();
        result.put("token",token);
        result.put("user",adUserVO);
        return ResponseResult.okResult(result);
    }
}
